package com.order.utils;

import java.sql.Connection;
import java.sql.SQLException;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.DbKit;

/** 
* @ClassName: Transaction 
* @Description: 数据库连接工具类，手动提交事务
* @author LinBo
* @date 2014年4月21日 下午6:00:50 
*  
*/ 
public class Transaction {

	private Connection conn;
	public void openConnection() throws SQLException{
		if(DbKit.getThreadLocalConnection() != null){
			throw new ActiveRecordException("不支持嵌套事务!");
		}
		conn = DbKit.getDataSource().getConnection();
		DbKit.setThreadLocalConnection(conn);
		//设置事务等级2
		conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
		//设置不自动提交
		conn.setAutoCommit(false);
	}
	
	public void commit(){
		if(conn == null){
			return;
		}
		try {
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void rollback(){
		if(conn == null){
			return;
		}
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void closeConnection(){
		try {
			if(conn != null){
				//恢复自动提交
				conn.setAutoCommit(true);
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DbKit.removeThreadLocalConnection();
		}
	}
}
